package com.juntuo.platformUtils;

import com.alibaba.fastjson.JSON;
import com.juntuo.Enums.Constants;
import com.juntuo.entity.Device;
import com.juntuo.util.HttpsUtil;
import com.juntuo.util.StreamClosedHttpResponse;

import java.util.HashMap;
import java.util.Map;

public class QueryDeviceDataUtil {

    public static Device query(String deviceId) throws Exception {

        // Two-Way Authentication
        HttpsUtil httpsUtil = new HttpsUtil();
        httpsUtil.initSSLConfigForTwoWay();

        // Authentication，get token
        String accessToken = AuthenticationUtil.login(httpsUtil);


        //Please make sure that the following parameter values have been modified in the Constant file.
        String appId = Constants.APP_ID;

        //please replace the deviceId, when you use the demo.
//        String deviceId = "8af24895-edac-4acb-9527-a58cf5f1c693";
        String urlQueryDeviceData = Constants.QUERY_DEVICE_DATA + "/" + deviceId;

        Map<String, String> paramQueryDeviceData = new HashMap<>();
        paramQueryDeviceData.put("appId", appId);

        Map<String, String> header = new HashMap<>();
        header.put(Constants.HEADER_APP_KEY, appId);
        header.put(Constants.HEADER_APP_AUTH, "Bearer" + " " + accessToken);

        StreamClosedHttpResponse bodyQueryDeviceData = httpsUtil.doGetWithParasGetStatusLine(urlQueryDeviceData,
                paramQueryDeviceData, header);

        System.out.println("QueryDeviceData, response content:");
        System.out.print(bodyQueryDeviceData.getStatusLine());
        System.out.println(bodyQueryDeviceData.getContent());

        Map<String,Object> map11= (Map<String, Object>) JSON.parse(bodyQueryDeviceData.getContent());
        Device device=DeviceMap2DeviceUtil.toDeviceData(map11);
//         = new DeviceData();
//        deviceData.setDeviceId((String) map11.get("deviceId"));
//        Map<String,Object> deviceInfo= (Map<String, Object>)map11.get("deviceInfo");
//        deviceData.setName((String)deviceInfo.get("name"));
//        List<Map<String,Object>> services =(List<Map<String,Object>>) map11.get("services");
//        for(Map<String,Object> service:services){
//            Map<String,Object> data = (Map<String,Object>)service.get("data");
//            if("VehicleDetectorBasic".equals((String)service.get("serviceId"))){
//                deviceData.setNumber((String)data.get("number"));
//                deviceData.setStatus((String)data.get("status"));
//            }else if("Battery".equals((String)service.get("serviceId"))){
//                deviceData.setBatteryLevel((Integer)data.get("batteryLevel"));
//            }
//        }

        return device;
//        System.out.println();
    }

    public static void main(String[] args) throws Exception {
        Device device = QueryDeviceDataUtil.query("8af24895-edac-4acb-9527-a58cf5f1c693");
        System.out.println();
    }

}
